console.log('start init app...');

// 基础库组件
let baseLibs = ["header", "utils", "gitee", "base64"];

// 加载HTML中的配置信息
let {
    needLogin = true,
    jsBaseDir = "", // 组件根目录
    minify = true, // 是否访问压缩的JS
    routeLibs = [],  // 本地路由组件
    otherLibs = [],  // 本地基础组件
    cssLibs = [],  // 需要注入的本地样式
    configFile = '' // 应用的配置文件路径
} = window.config;


if (needLogin && !localStorage.getItem("wyd-login-state")) {
    window.location.href = minify ? "/login.min.html" : "/login.html";
} else {
    requireJsConfig();
    startVueApp();
}

// requirejs配置
function requireJsConfig() {

    // 本地js定义
    let localLibs = routeLibs.concat(otherLibs);
    let localPath = {};

    for (let lib of baseLibs) {
        localPath[lib] = `/libs/common/${minify ? lib + ".min" : lib}`;
    }

    for (let lib of localLibs) {
        localPath[lib] = `/libs/${jsBaseDir}/${minify ? lib + ".min" : lib}`;
    }

    console.log('local js path : ', localPath);

    // 本地css定义
    let localCssList = cssLibs;
    let localCssPath = [];
    for (let css of localCssList) {
        localCssPath.push(minify ? `css!/css/${css}` + ".min.css" : `css!/css/${css}.css`);
    }

    // 路径配置
    require.config({
        urlArgs: !minify ? "bust=" + (new Date()).getTime() : '',
        map: {
            '*': {
                'css': '/cdn/css.min.js',
            }
        },
        // 定义模块 名称key-路径value
        paths: {
            "vue": "/cdn/vue/vue.min",
            "vueRouter": "/cdn/vue/vue-router",
            "axios": "/cdn/axios.min",
            "ELEMENT": "/cdn/element-ui/lib/index",
            "jquery": '/cdn/bootstrap/jquery.min',
            "semantic": '/cdn/semantic/semantic.min',
            "vs": '/cdn/monaco-editor/min/vs',
            "vue-markdown": '/cdn/vue/vue-markdown.min',
            "markdownIt": '/cdn/markdown-it.min',
            "dexie": '/cdn/dexie.min',
            ...localPath
        },
        // 默认自动加载的模块
        deps: [
            "vue", "vueRouter", "axios", "ELEMENT", "jquery", "semantic",
            "css!/cdn/element-ui/lib/theme-chalk/index.css",
            "css!/cdn/element-ui/lib/theme-chalk/display.css",
            "css!/cdn/semantic/semantic.min.css",
            ...localCssPath
        ],
        // 加载非AMD规范的JS文件
        shim: {
            "semantic": {
                deps: ['jquery']
            }
        }
    });
}

let appcfg = {};
// 启动APP
function startVueApp() {
    require([
        'vue', 'vueRouter', 'ELEMENT', 'axios',
        'gitee'
    ], function (
        Vue, VueRouter, element, axios,
        gitee
    ) {
        axiosInit(axios, utils);
        Vue.use(element);
        Vue.use(VueRouter);
        vueMixin();
        gitee.initState().then(() => {
            gitee.getFileContent(configFile, false, true).then(data => {
                appcfg = data;
                console.log('配置文件信息：', appcfg);
                window.wyd2021 = new Vue({
                    el: "#root",
                    router: vueRouterInit(gitee, VueRouter, element),
                    data() {
                        return {
                            active: "",
                            title: "",
                            menus: appcfg.menus,
                            basecfg: appcfg.base,
                            isSmallScreen: false,
                            asyncOperations: [],
                            cpsOperations: {},
                        }
                    },
                    components: {
                    },
                    watch: {
                        $route(newVal, oldVal) {
                            const match = (link) => {
                                if (link[2] === newVal.path.substr(1)) {
                                    this.active = link;
                                    document.title = `${link[0]}${link[3] ? ' - ' + link[3] : ''}`;
                                    return true;
                                }
                                return false;
                            }
                            for (let item of appcfg.menus) {
                                if (typeof item[2] === 'string') {
                                    if (match(item)) return;
                                } else {
                                    for (let link of item[2]) {
                                        if (match(link)) return;
                                    }
                                }

                            }
                        }
                    },
                    methods: {
                        showMenu() {
                            $('#sidebar').sidebar('show');
                        },
                        hideMenu() {
                            $('#sidebar').sidebar('hide');
                        },
                        route(name) {
                            if (name.startsWith("/") || name.startsWith("http")) {
                                window.open(name);
                                this.hideMenu();
                                return;
                            }
                            if (name === this.active) {
                                this.hideMenu();
                                return;
                            };
                            this.$router.push(name);
                            this.hideMenu();
                        },
                        asyncLoadOperations() {
                            gitee.getFileContent(`cps/operations.js`).then(data => {
                                // 动态注入脚本
                                let script = document.createElement('script');
                                script.type = 'text/javascript';
                                script.append(data);
                                document.body.appendChild(script);
                                require(["cps_operations"], (data) => {
                                    this.cpsOperations = data;
                                });
                            });
                        },
                    },
                    mounted() {
                        console.log('app mounted ...', this);
                        this.asyncOperations = appcfg.asyncOperations;
                        this.asyncLoadOperations();
                        this.isSmallScreen = document.documentElement.clientWidth < 600;
                        $('#sidebar').sidebar({
                            onHide() {
                                document.querySelector("#sidebar").scrollTo(0, 0);
                            }
                        });

                        /* !this.isSmallScreen &&  */$("#wyd-menu .dropdown").dropdown({
                            on: 'hover',
                            action: function (text, value) {
                                $(this).dropdown('hide');
                            }
                        });
                    },
                    template: /*html*/`
                    <div id="appWrapper">

                        <div class="ui sidebar right" id="sidebar">
                            <div class="ui vertical menu large w-100 min-vh-100 inverted">
                                <div class="item">
                                    <a class="header" @click="route(basecfg.defaultRoute.substr(1))">
                                        <img src="/imgs/logo.cat1.png" class="ui avatar medium image">
                                    </a>
                                </div>

                                <template v-for="item in menus">
                                    <a v-if="typeof item[2]==='string'" class="item" :class="active[2]===item[2]?'active':''" @click="route(item[2])">
                                        <i class="icon" :class="item[1]===''?'html5':item[1]"></i>{{item[0]}}
                                    </a>
                                    <div v-else class="item">
                                        <div class="header text-center"><i class="icon large" :class="item[1]===''?'html5':item[1]"></i>{{item[0]}}</div>
                                        <div class="menu">
                                            <a class="item" :class="active[2]===link[2]?'active':''" v-for="link in item[2]" @click="route(link[2])">
                                                <i class="icon" :class="link[1]===''?'html5':link[1]"></i>{{link[0]}}
                                            </a>
                                        </div>
                                    </div>
                                </template>
                                <div class="item">
                                    <div class="header text-center"><i class="ui icon paper plane outline large"></i>快捷操作</div>
                                    <div class="menu">
                                        <a class="item" v-for="operation in asyncOperations" @click="cpsOperations[operation[1]]()">
                                            <i class="icon large" :class="operation[2]?operation[2]:'code'"></i>{{operation[0]}}
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex flex-column push" id="context">
                            
                            <div class="ui menu" id="wyd-menu">
                                <div class="item ui dropdown icon">
                                    <a><i class="icon large" :class="active[1]?active[1]:'content black'"></i></a>
                                    <div class="menu">
                                        <template v-for="item in menus">
                                            <a v-if="typeof item[2]==='string'" class="item" :class="active[2]===item[2]?'active':''" @click="route(item[2])">
                                                <i class="icon" :class="item[1]===''?'html5':item[1]"></i>{{item[0]}}
                                            </a>
                                            <div v-else class="item">
                                                <span class="text"><i class="icon" :class="item[1]==='' ? 'blue html5' : item[1]"></i>{{item[0]}}</span>
                                                <i class="dropdown icon"></i>
                                                <div class="menu">
                                                    <a class="item" :class="active[2]===link[2]?'active':''" v-for="link in item[2]" @click="route(link[2])">
                                                        <i class="icon" :class="link[1]===''?'html5':link[1]"></i>{{link[0]}}
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="divider" v-if="item[4]"></div>    
                                        </template>
                                        <div class="item">
                                            <span class="text"><i class="ui icon paper plane outline large blue"></i>快捷操作</span>
                                            <i class="dropdown icon"></i>
                                            <div class="menu">
                                                <a class="item" v-for="operation in asyncOperations" @click="cpsOperations[operation[1]]()">
                                                    <i class="icon large" :class="operation[2]?operation[2]:'code'"></i>{{operation[0]}}
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="item flex-grow-1 justify-content-center">
                                    <h3 class="ui header">
                                        <div class="text-center" :title="active[3]?active[3]:active[0]">{{active[0]}}</div>
                                    </h3>
                                </div>

                                <div class="right menu">
                                    <a class="item" @click="showMenu"><i class="paper plane icon large blue"></i></a>
                                </div>
                            </div>

                            <div class="flex-grow-1">
                                <keep-alive>
                                    <router-view></router-view>
                                </keep-alive>
                            </div>
                        </div>
                    </div>
                `
                });
            });
        })


    })
}


function vueRouterInit(gitee, VueRouter, element) {

    const routeNames = routeLibs;
    const routes = [
        { path: '/', redirect: appcfg.base.defaultRoute }
    ]

    // 动态路由配置，访问路由时才加载js
    for (let routeName of routeNames) {
        routes.push({
            path: `/${routeName}`, component: resolve => {
                require([routeName], (data) => {
                    if (data.cps) {
                        resolve(data.cps);
                    } else {
                        resolve(data);
                    }
                });
            }
        });
    }

    // 动态路由，自动加载 cps 路径下的js文件绑定到路由下
    let autoRouteList = appcfg["autoRouteList"];
    if (autoRouteList) {
        try {
            for (let autoRoute of autoRouteList) {
                let meRoute = `ar_${autoRoute}`;
                routes.push({
                    path: `/${meRoute}`, component: resolve => {
                        gitee.getFileContent(`cps/${autoRoute}.js`).then(data => {
                            // 动态注入脚本
                            let script = document.createElement('script');
                            script.type = 'text/javascript';
                            script.append(data);
                            document.body.appendChild(script);
                            require([meRoute], (data) => {
                                if (data.cps) {
                                    resolve(data.cps);
                                } else {
                                    resolve(data);
                                }
                            });
                        });
                    }
                });
            }
        } catch (e) {
            console.error(e);
        }
    }
    console.log('routes info ', routes);
    let router = new VueRouter({
        routes
    });

    // 配置路由加载时的提示信息
    let loading;
    let loadedRoute = [];

    router.beforeEach((to, from, next) => {
        if (!loadedRoute.includes(to.path)) {
            loading = element.Loading.service({
                lock: true,
                text: 'Loading~~~',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.9)'
            });
            setTimeout(() => {
                loading.close();
            }, 3000)
        }
        next();
    });

    router.afterEach((to, from) => {
        if (!loadedRoute.includes(to.path)) {
            loadedRoute.push(to.path);
            loading && loading.close();
        }
    });
    return router;
}

// axios拦截器初始化
function axiosInit(axios, utils) {
    axios.interceptors.request.use(function (config) {
        return config;
    }, function (error) {
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function (response) {
        if (response.status === 200) {
            return response.data;
        }
        return response;
    }, function (error) {
        if (error.response && error.response.status === 401) {
            utils.goLogin();
        }
        return Promise.reject(error);
    });
}

// 将Vue组件中HTML根节点有wydFlag属性的统一注入，方便后面通过标记获取组件
function vueMixin() {
    require(['vue', 'utils'], (Vue, utils) => {
        // 全局混入
        Vue.mixin({
            mounted() {
                if (!this.$el.getAttribute) {
                    return;
                }
                let wydFlag = this.$el.getAttribute("wydFlag");
                if (wydFlag) {
                    utils.setVueCps(wydFlag, this);
                }
            }
        })
    })
}